import hashlib

from django import forms
from django.contrib.auth.forms import UserCreationForm

from .models import CustomUser


class UserForm(UserCreationForm):
    mobile = forms.CharField(
        label="手机号码",
        max_length=11,
        widget=forms.TextInput(attrs={'class':'form-control','placeholder':'请输入手机号码'})
    )

    class Meta:
        model=CustomUser
        fields = ['mobile', 'password1', 'password2']

    def clean_mobile(self):
        mobile = self.cleaned_data.get('mobile')
        exists = CustomUser.objects.filter(mobile=mobile).exists()
        if exists:
            raise forms.ValidationError('该手机号码已被注册！')
        return mobile

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password1')
        mobile = cleaned_data.get('mobile')
        password_hash = hashlib.md5((mobile[0]+mobile[2]+password+mobile[5]+mobile[4]).encode()).hexdigest()
        cleaned_data['password_hash'] = password_hash
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        user.password = self.cleaned_data.get('password_hash')
        if commit:
            user.save()
        return user


class LoginUserForm(forms.Form):
    mobile = forms.CharField(
        label="手机号码",
        max_length=11,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入手机号码'})
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'})
    )


    def clean(self):
        cleaned_data = super().clean()
        mobile = cleaned_data.get('mobile')
        password = cleaned_data.get('password')
        # 加密密码
        password_hash = hashlib.md5((mobile[0]+mobile[2]+password+mobile[5]+mobile[4]).encode()).hexdigest()

        # 查询用户
        try:
            user = CustomUser.objects.get(mobile=mobile)
        except CustomUser.DoesNotExist:
            raise forms.ValidationError('用户不存在')

        # 验证密码
        if user.password != password_hash:
            raise forms.ValidationError('密码错误')

        cleaned_data['user'] = user  # 将用户对象存储到 cleaned_data 中
        return cleaned_data


